package com.qf.tomcat;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TomcatServer {

    public static HashMap<String,HttpServlet> servletHashMap;
    public static ServerSocket serverSocket;
    public HttpRequestAndResponse httpRequestAndResponse;
    private ExecutorService service;

    public TomcatServer(){
        try {
//            HttpServlet httpServlet = null;
            serverSocket= new ServerSocket(8080);
            System.out.println("tomcat start");
            System.out.println("Scan All Servlet");
            TomcatWebServletScan tomcatWebServletScan = new TomcatWebServletScan();
            servletHashMap=tomcatWebServletScan.servletScan();

           httpRequestAndResponse=new HttpRequestAndResponse(servletHashMap);
            service = Executors.newFixedThreadPool(100);
        }catch (IOException e){
            e.printStackTrace();
        }catch (URISyntaxException e){
            e.printStackTrace();
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }catch (IllegalAccessException e){
            e.printStackTrace();
        }catch (InstantiationException e){
            e.printStackTrace();
        }
    }

    private void start() throws IOException{
        while (true){
            final Socket socket = serverSocket.accept();
//            new Thread(new RequestRunnable(socket,httpRequestAndResponse)).start();
            service.execute(new RequestRunnable(socket,httpRequestAndResponse));
        }
    }

    public static void main(String[] args) throws IOException,ClassNotFoundException,URISyntaxException,IllegalAccessException,InstantiationException{
        TomcatServer tomcatServer = new TomcatServer();
        tomcatServer.start();
    }
}
